<?php
namespace app\push;
use think\worker\Server;
use Channel\Server as Channel_Server;
use Channel\Client;

//订阅
class On extends Server{
	protected $socket = 'Websocket://0.0.0.0:3333';
	protected $option = ['name'=>'on'];

	public function onWorkerStart($worker){
		 //echo 'websoket服务启动成功'."\n";
		 //Channel客户端连接到Channel服务端
		Client::connect('127.0.0.1',1111);
		 //单个用户订阅broadcast事件，并注册事件回调
		Client::on($worker->id,function($data)use($worker){
			 $connection = $worker->connections[$data['connection_id']];
			 $connection->send($data['content']);
		 });
		 //网站链接用户订阅事件，广播
		 Client::on('broadcast',function($data)use($worker){
			 foreach($worker->connections as $conn){
				 $conn->send($data['content']);
			 }
		 });
	}

	public function onMessage($connection,$data)
	{
		echo "客户端发来信息：".$data."";
		//服务端响应后回调给用户端发送信息
		$connection->send("服务端已收到你的".$data."来信");
	}
	

	
	public function onConnect($connection){
		//$connection->send("握手成功，链接已建立，服务端发来贺电");
		//echo $connection->getRemoteIp()."的客户端链接上了". "\n";
		$connection->send('connection_id='.$connection->id.' worker_id='.$this->worker->id);
	}
	
	/* public function onClose($connection){
		echo 'websoket服务端关闭'."\n";
	}  */
	
}
	// 初始化一个Channel服务端
	new Channel_Server('127.0.0.1',1111);
